
package com.sun.showcase.biz.mall.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sun.showcase.exception.BusinessException;
import com.sun.showcase.biz.mall.dao.MemberDao;
import com.sun.showcase.biz.mall.service.MemberLevelService;
import com.sun.showcase.biz.mall.service.MemberService;
import com.sun.showcase.client.domain.mall.Member;
import com.sun.showcase.client.query.mall.MemberLevelQuery;
import com.sun.showcase.client.query.mall.MemberQuery;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.utils.ExecuteResult;
import com.sun.showcase.utils.StringConstant;
import com.sun.showcase.utils.UuidUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("memberService")
@Transactional
public class MemberServiceImpl implements MemberService{
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private MemberLevelService memberLevelService;
	
	public void setMemberDao(MemberDao dao) {
		this.memberDao = dao;
	}

	public DataGrid datagrid(MemberQuery memberQuery) {
		DataGrid j = new DataGrid();
		Pager<Member> pager  = find(memberQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private List<MemberQuery> getQuerysFromEntitys(List<Member> members) {
		List<MemberQuery> memberQuerys = new ArrayList<MemberQuery>();
		if (members != null && members.size() > 0) {
			for (Member tb : members) {
				MemberQuery b = new MemberQuery();
				BeanUtils.copyProperties(tb, b);
				memberQuerys.add(b);
			}
		}
		return memberQuerys;
	}

	private Pager<Member> find(MemberQuery memberQuery) {
		Page<Member> page = PageHelper.startPage(memberQuery.getPage().intValue(), memberQuery.getRows().intValue());
		List<Member> list = memberDao.findList(memberQuery);
		Pager<Member> pager = new Pager<Member>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return  pager;
		
	}
	


	public Member add(MemberQuery memberQuery) {
		Member t = new Member();
		BeanUtils.copyProperties(memberQuery, t);
		t.setCreateDate(new Date());
	    t.setId(UuidUtil.get32UUID());
	    t.setBalance(0D);
	    t.setFrozenBalance(0D);
	    t.setAgentFlag("0");
		memberDao.save(t);
		memberQuery.setId(t.getId());
		if(StringUtils.isNotBlank(memberQuery.getFatherId())) {
			Member f = this.get(memberQuery.getFatherId());
			if(f != null)
			memberLevelService.buildTree(t, f);
		}
		return t;
		
	}

	public void update(MemberQuery memberQuery) {
		Member t = memberDao.getById(memberQuery.getId());
	    if(t != null) {
	    	BeanUtils.copyProperties(memberQuery, t);
	    	memberDao.update(t);
		}
	}
	
	/**
	 * 根据条件更新部分字段   新建一个query封装需要更新的字段
	 * searchMap封装更新条件
	 * */
	public void updatePart(MemberQuery memberQuery) {
	    memberDao.updatePart(memberQuery);
	}

	public void delete(String[] ids) {
		memberDao.deleteAc(ids);
	}

	//逻辑删除 更新状态位
	public void deletePt(String[] ids) {
		memberDao.deletePt(ids);
	}

	public Member get(MemberQuery memberQuery) {
		return memberDao.getById(memberQuery.getId());
	}

	public Member get(String id) {
		return memberDao.getById(id);
	}

	
	public List<MemberQuery> listAll(MemberQuery memberQuery) {
	    List<Member> list = memberDao.findList(memberQuery);
		List<MemberQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}
	
	@Override
	public Member save(MemberQuery query) {
		
		MemberQuery q = new MemberQuery();
		
		q.setPhone(query.getPhone());//手机号唯一验证
		List<MemberQuery> l = this.listAll(q);
		
		
		if(null!=l && l.size()>0) {//更新
			if(l.size()==1 && StringUtils.isEmpty(l.get(0).getOpenid())) {
				//没绑定openid
				MemberQuery update = new MemberQuery();
				update.getSearchMap().put(StringConstant.ID, l.get(0).getId());
				update.setOpenid(query.getOpenid());
				if(StringUtils.isEmpty(l.get(0).getHeadImage())) {
					update.setHeadImage(query.getHeadImage());
				}
				if(StringUtils.isEmpty(l.get(0).getNickName())
						|| l.get(0).getNickName().equals(l.get(0).getPhone())) {
					update.setNickName(query.getNickName());
				}
				return this.get(l.get(0).getId());
			}else {
				throw new BusinessException("该手机号已注册！");
			}
			
		}else {
			
			return this.add(query);
			
		}
		
	}

	@Override
	public ExecuteResult<Member> loginWithPhoneAndPwd(MemberQuery query) {
		ExecuteResult<Member> res = new ExecuteResult<Member>();
		if(StringUtils.isEmpty(query.getPhone())
				|| StringUtils.isEmpty(query.getPassword())) {
			res.addErrorMessage("用户或名密码错误！");
			return res;
		}
		Member mem = this.memberDao.getByPhone(query.getPhone());
		if(mem == null) {
			//不存在 ，注册
			MemberQuery memberQuery = new MemberQuery();
			memberQuery.setPhone(query.getPhone());
			memberQuery.setNickName(query.getPhone());
			memberQuery.setPassword(query.getPassword());
			mem = this.add(memberQuery);
			res.setResult(mem);
			return res;
		}
		if(!query.getPassword().equals(mem.getPassword())) {
			res.addErrorMessage("用户或名密码错误！");
			return res;
		}
		res.setResult(mem);
		return res;
	}

	@Override
	public ExecuteResult<Member> registWithPhoneAndPwd(MemberQuery query) {
		ExecuteResult<Member> res = new ExecuteResult<Member>();
		if(StringUtils.isEmpty(query.getPhone())
				|| StringUtils.isEmpty(query.getPassword())) {
			res.addErrorMessage("用户或名密码无效！");
			return res;
		}
		Member mem = this.memberDao.getByPhone(query.getPhone());
		if(mem == null) {
			//不存在 ，注册
			MemberQuery memberQuery = new MemberQuery();
			memberQuery.setPhone(query.getPhone());
			memberQuery.setNickName(query.getPhone());
			memberQuery.setPassword(query.getPassword());
			mem = this.add(memberQuery);
			res.setResult(mem);
			return res;
		}else {
			res.addErrorMessage("该手机已注册！");
			return res;
		}
	}

	@Override
	public Long updateBalance(String id, Double balance, Double frozenBalance) {
		return memberDao.updateBalance(id, balance, frozenBalance);
	}

	@Override
	public void toBeAgent(String id) {
		MemberQuery up = new MemberQuery();
		up.getSearchMap().put(StringConstant.ID, id);
		up.setAgentFlag(StringConstant.ONE);
		this.updatePart(up);
		MemberLevelQuery ml = new MemberLevelQuery();
		ml.getSearchMap().put("parent_id", id);
		ml.setParentAgentFlag(StringConstant.ONE);
		memberLevelService.updatePart(ml);
	}
	
	
}
